﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cronos.DateTimeExtensions
{
    public static class WeekExtensions
    {
        public static DateTime AddWeek(this DateTime source, int weeks)
        {
            return source.AddDays(weeks * 7);
        }

        public static DateTime FirstDayOfWeek(this DateTime source)
        {
            return source.FirstDayOfWeekFrom(DayOfWeek.Sunday);
        }

        public static DateTime FirstWorkDayOfWeek(this DateTime source)
        {
            return source.FirstDayOfWeekFrom(DayOfWeek.Monday);
        }

        public static DateTime FirstDayOfWeekFrom(this DateTime source, DayOfWeek fromDayWeek)
        {
            if (source.DayOfWeek == fromDayWeek) return source;

            var currentDate = source;

            do { currentDate = currentDate.AddDays(-1); }
            while (currentDate.DayOfWeek != fromDayWeek);

            return currentDate;
        }

        public static DateTime LastDayOfWeek(this DateTime source)
        {
            return source.LastDayOfWeekFrom(DayOfWeek.Saturday);
        }

        public static DateTime LastWorkDayOfWeek(this DateTime source)
        {
            return source.LastDayOfWeekFrom(DayOfWeek.Friday);
        }

        public static DateTime LastDayOfWeekFrom(this DateTime source, DayOfWeek fromDayWeek)
        {
            if (source.DayOfWeek == fromDayWeek) return source;

            var currentDate = source;

            do { currentDate = currentDate.AddDays(1); }
            while (currentDate.DayOfWeek != fromDayWeek);

            return currentDate;
        }
    }
}
